package com.lbx;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lbx create by 2021/6/8 14:30
 * @apiNote MyConfig
 */
@Configuration
public class MyConfig implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        String token=null;
        if (request.getHeader("Authorization")!=null&&!request.getHeader("Authorization").equals("null")){
            token = request.getHeader("Authorization");
        }
        String requestURI = request.getRequestURI();
        if (token!=null&&!token.equals("null")){
            DecodedJWT decode = JWT.decode(token);
            Claim loginUser = decode.getClaims().get("loginUser");
            Map<String, Object> map = loginUser.asMap();
            HttpSession session = request.getSession();
            session.setAttribute("loginUser",map);
            return true;
        }else {
            if (requestURI.equals("/") ||requestURI.equals("/index")){
                return true;
            }
            System.err.println("token is null");
            response.setCharacterEncoding("UTF-8");
            PrintWriter printWriter = response.getWriter();
            HashMap<String, Object> map = new HashMap<>();
            map.put("status",401);
            map.put("message","您还没有登录");
            map.put("data",null);
            printWriter.write(JSON.toJSONString(map));
            printWriter.flush();
            printWriter.close();
            return false;
        }
    }
}
